<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<link rel="stylesheet" type="text/css" href="css/main.css" />
<link rel="stylesheet" type="text/css" href="css/jquery-ui-1.8.12.custom.css"/>

<!--   <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>  --> 
<script type="text/javascript" src="js/jquery-1.6.min.js"></script>
  
   
<script type="text/javascript" src="js/jquery-ui-1.8.12.custom.min.js"></script>        
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="js/gmap3.min.js"></script> 


<style>
  *{
    font-family: verdana;
    font-size: 12px;
  }
  body{
    text-align:center;
  }
  .gmap3{
    margin: 20px auto;
    border: 1px dashed #C0C0C0;
    width: 1000px;
    height: 500px;
  }
  .ui-menu .ui-menu-item{
    text-align: left;  
    font-weight: normal;
  }
  .ui-menu .ui-menu-item a.ui-state-hover{
    border: 1px solid red; 
    background: #FFBFBF; 
    color: black;
    font-weight:bold;
  }
</style>  


   <script type="text/javascript">
   
//   jQuery.noConflict();
   
    var addressFound = false;
    var latLngAddress = "";
    var lat;
    var lng;
    
   
 $(document).ready(function() {
	   
	   $("#searchText").keyup(eventSearchVille);
	   $('[name="ville"]').keyup(eventSearchVille);
	   
	//   $("#save").click(test);
	
	  // $("#testButton").click(test);
	   
	   
	   
/*	   
   $("#searchText").keyup(function(event){
	   $('#divResults').show();
	   var stext = $("#searchText").val();  
	   //alert("searchText : "+stext);
       $.post("services.php", {"searchText":$("#searchText").val()},  function(data) { // {searchText:'ni'},  test.json
    	 //  alert("found"+data);    	   
         // $('#results').html('<p> Name: '+data[0].ville  + '</p>');
          $('#divResults').html('');    
          $.each(data,function(ind,val){
            	 $('#divResults').append('<p id=\'idVille_'+data[ind].id+'\'>' + data[ind].ville + '</p>');
            	 
             });
         
          customResults();
          
       },"json");
   });*/
   
   $("#save").click(function(event){
	   if(verifFormAddResto()){
		   
	//   alert("latLngAddress = "+latLngAddress);
	   
	   $.post("services.php", 
			   {
		   "action":"save",
		   "nom":$('[name="nom"]').val(),
		   "adresse":$('[name="adresse"]').val(),
		   "codePostal":$('[name="codePostal"]').val(),
		   "ville":$('[name="ville"]').val()	  
			   },
			   function(data) {				   
				   $('#divSave').html('Enregistrement : '+data.res);    
	   },"json");
	   
	   }
	   
   });
   
   $("#saveResto").click(function(event){
	   if(verifFormAddResto()){
		   
	//	   alert("latLngAddress = "+latLngAddress);
		   
		//alert("street :" +street);	   
		   
	  // alert("nom = "+$('#nomResto').val());
	  // alert("addressGoogle = "+$('#addressGoogle').val());
	   
	   $.post("services.php", 
			   {
		   "action":"saveResto",
		   "nom":$('#nomResto').val(),
		   "adresse":$('#addressGoogle').val(),
		   "latAddress":latAddress,
		   "lngAddress":lngAddress 
		   },
			   function(data) {				   
				   $('#divSaveResto').html('Enregistrement : '+data);    
	   });
	   
	   }
	   
   });
   
   
   
   
   $("#testGoogle").gmap3(
		   {
			   action:'init',
			   options:{ 
	               center:[46.578498,2.457275], 
	               zoom: 5 
          	 }, 
		   		events:{
					bounds_changed:function(map, event, data){
				         // alert(map.getBounds().toString());
						updateMapWithResto(map.getBounds());
				         
			        }
				
			   }
		   }
   );

  
   
   $('#addressGoogle').autocomplete({
     //This bit uses the geocoder to fetch address values
     source: function(request, response) {
       $("#testGoogle").gmap3({
         action:'getAddress',
         address: request.term,
         callback:function(results){
           if (!results) 
        	   {
        	   addressFound = false;
        	   return;        	   
        	   }
          // street = results[1].formatted_address;
           addressFound = true;          
           
           response($.map(results, function(item) {
        	   
        	//alert("item:"+item.formatted_address);  
        	   
             return {
               label:  item.formatted_address,
               value: item.formatted_address,
               latLng: item.geometry.location
             }
           }));
         }
       });
     },
     //This bit is executed upon selection of an address
     select: function(event, ui) {
       $("#testGoogle").gmap3(
         {action:'clear', name:'marker'},
         {action:'addMarker',
           latLng:ui.item.latLng,
           map:{center:true,zoom:getZoom(ui.item.value)}
         }
       );
       addressFound = true;
       latAddress = ui.item.latLng.lat();
       lngAddress = ui.item.latLng.lng();
       
     }
   });
   
   $('#searchResto').autocomplete({
	     //This bit uses the geocoder to fetch address values
	     source: function(request, response) {
	       $("#testGoogle").gmap3({
	         action:'getAddress',
	         address: request.term,
	         callback:function(results){
	           if (!results) 
	        	   {	        	   
	        	   return;        	   
	        	   }
	          // street = results[1].formatted_address;
	           //addressFound = true;          
	           
	           response($.map(results, function(item) {
	        	   
	        	//alert("item:"+item.formatted_address);  
	        	   
	             return {
	               label:  item.formatted_address,
	               value: item.formatted_address,
	               latLng: item.geometry.location
	             }
	           }));
	         }
	       });
	     },
	     //This bit is executed upon selection of an address
	     
	     select: function(event, ui) {
	    	
	       $("#testGoogle").gmap3(
	         {action:'clear', name:'marker'},
	         {action:'addMarker',
	           latLng:ui.item.latLng,
	           map:{center:true,zoom:getZoom(ui.item.value)}
	         }
	       );
	       //addressFound = true;
	       //latLngAddress = ui.item.latLng.toUrlValue();
	       //updateMapWithResto(ui.item.latLng);
	     }
	   });
   
   });

function updateMapWithResto(latLngBound)
 {
	// alert("updateMapWithResto "+ latLngBound.toString());
	 
	 
	 $.post("services.php", 
			   {
		   "action":"getResto",		   
		   "latRight":latLngBound.getNorthEast().lat(),
		   "latLeft":latLngBound.getSouthWest().lat(),
		   "lngRight":latLngBound.getNorthEast().lng(),
		   "lngLeft":latLngBound.getSouthWest().lng()
		   },
			   function(data) {
				   //$('#divDEBUG').html('DEBUG : '+data[0].data.nom);
				
				   displayResto(data);				    
				   
				   $("#testGoogle").gmap3(
					         {action:'clear', name:'marker'},
					         {action:'addMarkers',
					          markers: data,					         
					         marker:{
					             options:{
					               draggable: false,
					               icon: new google.maps.MarkerImage("img/resto.jpeg")
					             },
					             events:{
					               mouseover: function(marker, event, data){
					                 var map = $(this).gmap3('get'),
					                     infowindow = $(this).gmap3({action:'get', name:'infowindow'});
					                 if (infowindow){
					                   infowindow.open(map, marker);
					                   infowindow.setContent(data.nom);
					                 } else {
					                   $(this).gmap3({action:'addinfowindow', anchor:marker, options:{content: data.nom}});
					                 }
					               },
					               mouseout: function(){
					                 var infowindow = $(this).gmap3({action:'get', name:'infowindow'});
					                 if (infowindow){
					                   infowindow.close();
					                 }
					               }
					             }
					         }
					         }
					       );
				   
				   
				   
	   },"json");
	 
	// $('#divDEBUG').html('DEBUG : '+markersPos);
	 
 }

 function displayResto(listResto)
 {
	content = "";

	if(listResto.length > 0)
	{ 

		content = "<table border=1 cellspacing=1 cellpadding=1 width=\"50%\" id=TABLE1><tr><td>Liste des restaurants</td></tr>";
		
	 $.each(listResto, function(i,item){
		 //content +="nom :"+item.data.nom+"<br>";

		content += addRestoToTab(item.data);		
		 
       });

	}
	 $('#divListResto').html(content);
 }

 function addRestoToTab(resto) 
 {
	line = "<tr><td><table border=0 cellspacing=5 cellpadding=5 width=\"100%\"><tr><colgroup span=\"1\"width=\"70%\"/><td>";

	line += resto.nom;

	line += "</td><td>note</td></tr><tr><td colspan=\"2\">";
	line += resto.adresse;

	line += "</td></tr></table></td></tr>";

	return line;	


 }
 
 
 function getZoom(address){
	 splitAddress = address.split(',');
	 if(splitAddress.length > 2) {			 
		 	return 16;
	 }
	 else return 10;
 }
 
// $(function(){
   
  
//    });
   /*
   $(document).ready(function() {
      $("#driver").click(function(event){
          $.getJSON('result.json', function(jd) {
             $('#stage').html('<p> Name: ' + jd.name + '</p>');
             $('#stage').append('<p>Age : ' + jd.age+ '</p>');
             $('#stage').append('<p> Sex: ' + jd.sex+ '</p>');
             
             $.each(jd.ville,function(val){
            	 $('#stage').append('<p> Name: ' + val + '</p>');
             })
             
          });
      });
   });
   */
   
   function eventSearchVille(event){
		  // alert("eventSearchVille");
		   
		   id = event.target.id;
		   //divResults = $('#divResults_'+id);
		   
		   textBox = $(event.target);
		   divResults = textBox.next("div");
		   
		   divResults.show();
		   //var stext = $("#searchText").val();  
		   //alert("searchText : "+stext);
	       $.post("services.php", {"searchText":textBox.val()},  function(data) { // {searchText:'ni'},  test.json
	    	 //  alert("found"+data);    	   
	         // $('#results').html('<p> Name: '+data[0].ville  + '</p>');
	          divResults.html('');    
	          $.each(data,function(ind,val){
	        	  divResults.append('<p id=\'idVille_'+data[ind].id+'\'>' + data[ind].ville + '</p>');
	            	 
	             });
	         
	          customResults(divResults,textBox);
	          
	       },"json");
	   }
   function verifFormAddResto(){
		  //alert("verifFormAddResto");
		  
		  //$('[name="nom"]').toggleClass("cssErrorField");
		  
		  //$('[name="nom"]').val()=="" ? ($.noop();alert("value"): $('[name="nom"]').toggleClass("cssErrorField");alert("no value"));
		  
		  //$('[name="nom"]').val()=="" ? (alert("no value")): (alert("value"));
		  check = true;
		 
		  check &= verifField($("#nomResto"));
		  check &= verifField($("#addressGoogle"));
		  check &= addressFound;
		  
		  if(!addressFound){
			  $("#addressGoogle").toggleClass("cssErrorField");
		  }
		  else {
			  address = $("#addressGoogle").val();
			  splitAddress = address.split(',');
			  if(splitAddress.length < 3) {
				  $("#addressGoogle").toggleClass("cssErrorField");
				  check = false;
			  }
			  
			  
			  
		  }
		  
		  /*
		  check &= verifField("codePostal");	
		  check &= verifField("ville");
		  */
		  return check;
	  }
   
	 
	  function verifField(field){
		  
		//  field = $('[name="'+fieldName+'"]');
		//  field.removeClass("cssErrorField");
		   	
		applycss = (field.val()=="");
		
		 field.toggleClass("cssErrorField",applycss);
		 
		  return !applycss;
		  
	  }
	  
		  
		  function customResults(divResults,searchText) {
			  applycss = false;
			  
			  childs = divResults.children("p");
			  
			  
			  childs.mouseenter(function(event){
				  applycss = true;
				  childs.removeClass("cssSelected");
				  $(event.target).addClass("cssSelected");
				  
			  });
			  
			  childs.click(function(event){
				  searchText.val($(event.target).html());
				  
				  divResults.hide();
			  });
		
	  }
   
   
  
  
   
  
	  
   </script>
</head>

<body>
<h1>TEST RESTO WEB</h1>

<form name="formUser" id="formUser" height="100%" method="POST" align=center> <!-- action="resultat.php" -->
<table>
<tr>
<td>
Nom
</td>
<td>
<input type="text" name="nom"/>
</td>
</tr>
<tr>
<td>
Adresse
</td>
<td>
<input type="text" name="adresse"/>
</td>
</tr>
<tr>
<td>
Code Postal
</td>
<td>
<input type="text" name="codePostal"/>
</td>
</tr>
<tr>
<td>
Ville
</td>
<td>
<input type="text" name="ville"/>
<div id="divResults" class="cssDivResult"></div>
</td>
</tr>
</table> 

</form>

<button id="save">Enregistrer</button> <!--  type="submit" -->
<button id="testButton">test</button>

<div id="divSave">
</div>

<form action="">
 <input type="text" id="searchText" value="" />
   <div id="divResults" class="cssDivResult">   
   </div>
</form>

<table>
<tr>
<td>Nom du resto</td>
<td><input type="text" id="nomResto" size="60"></td>
</tr>
<tr>
<td>Adresse</td>
<td><input type="text" id="addressGoogle" size="60"></td>
</tr>
<tr>
<td colspan="2">
<button id="saveResto">Enregistrer</button>
<div id="divSaveResto"></div>
</td>
</tr>
</table>

<div id="testGoogle" class="gmap3"></div>

<table>
<tr>
<td>recherche resto</td>
<td><input type="text" id="searchResto" size="60"></td>
</tr>
</table>
<div id="divDEBUG"></div>
<div id="divListResto"></div>

</body>
</html>